package com.landary.parameterrplacement.utils;

import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 刘欣
 * @createTime 2023/8/1 15:44
 * @description xml转map
 */
@Slf4j
public class XmlToMapUtils {
    public static List<?> xmlToMap(String xml, String tagName) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));

            NodeList nodeList = document.getElementsByTagName("document");
            Element element = (Element) nodeList.item(0);
            String cdataContent = element.getTextContent();
//            log.info("cdataContent:"+cdataContent);

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(new StringReader(cdataContent));
            Document cdataDocument = builder.parse(inputSource);

            NodeList userNodes = cdataDocument.getElementsByTagName(tagName);
            List<Map<String, String>> listMap = new ArrayList<>();

            for (int i = 0; i < userNodes.getLength(); i++) {
                Node userNode = userNodes.item(i);
                if (userNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element userElement = (Element) userNode;
                    NodeList childNodes = userElement.getChildNodes();

                    Map<String, String> map = new HashMap<>();

                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node childNode = childNodes.item(j);
                        if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                            String childNodeTagName = childNode.getNodeName();
                            String textContent = childNode.getTextContent();
                            map.put(childNodeTagName, textContent);
                        }
                    }

                    listMap.add(map);
                }
            }
            return listMap;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
